#!/bin/bash
#
# Upload packages to launchpad. Note: you must configure dput for tvh-X
# as target PPA, and you should also define DEBFULLNAME and DEBEMAIL 
# environment variables
#

#set -x

# Terminate
function die
{
  echo >&2 "ERROR: $@"
  exit 1
}

# CMD
CMD=$(basename "$0")
DIR=$(cd $(dirname "$0"); pwd)

# Configuration
TVH_ROOT=$(cd "$(dirname "$0")"/..; pwd)

# Builds
[ -z "$TVH_BUILD" ] && TVH_BUILD="
trusty:i386:amd64
wily:i386:amd64
xenial:i386:amd64
wheezy:i386:amd64:armhf
jessie:i386:amd64:armhf
"

# Options
[ ! -z "$1" ] && REL=$1 || REL=master
[ ! -z "$2" ] && PPA=$2 || PPA=unstable

# Set default package
[ -z "$DEBEMAIL"    ] && DEBEMAIL="apt@tvheadend.org"
[ -z "$DEBFULLNAME" ] && DEBFULLNAME="Tvheadend (Package Signing Key)"
export DEBEMAIL
export DEBFULLNAME

# Setup
cd "$TVH_ROOT" || exit 1
NOW=`date -R`
CHANGELOG=./debian/changelog
VERFILE=./src/version.c

# Checkout
git checkout $REL || die "could not checkout $REL"

# Get version
VER=$("./support/version" $VERFILE)

# Export git tree
TMPDIR=/tmp/$CMD-$$
trap "rm -rf $TMPDIR" EXIT
mkdir -p "$TMPDIR"
git archive --prefix=tvheadend/ HEAD | tar -C "${TMPDIR}" -x ||\
  die "failed to archive git tree"
cd "$TMPDIR/tvheadend" || die "failed to enter archived tree"

cd ..

# For each distro
for b in $TVH_BUILD; do
  d=${b%%:*}
  arch=${b##${d}:}
  arch=${arch/:/ }

  # Update version
  V=${VER}~${d}
  mv tvheadend "tvheadend-${V}"
  cd "tvheadend-${V}"

  # Create changelog
  ./support/changelog "$CHANGELOG" "$d" "$VER" || exit 1

  # Build source package
  dpkg-buildpackage -d -I.git* -S -sgpg -pgpg || exit 1

  # Build
  if [ "$CMD" == "pbuilder" ]; then
    for a in ${arch}; do
      pbuilder-dist $d $a build ${PBUILDER_OPTS} ../tvheadend_${V}.dsc
    done

  # Upload
  else
    [ ! -f "$HOME/.dput.cf" ] && DPUT_OPT="$DPUT_OPT -c $DIR/dput.cf"
    dput $DPUT_OPT tvh-${PPA} ../tvheadend_${V}_source.changes || exit 1
  fi

  # Rename back
  cd ..
  mv "tvheadend-${V}" tvheadend
done
